﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AesUtils
{
    public class GZIPHelper
    {
        public string ReadGzipByBase64(string base64Content, string encoding = "utf-8")
        {
            string result = string.Empty;
            byte[] bytes = null;
            try
            {
                bytes = Convert.FromBase64String(base64Content);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                result = "base64格式不正确";
            }
            result = ReadGzip(bytes, encoding);

            return result;
        }

        private string ReadGzip(byte[] bytes, string encoding = "utf-8")
        {
            string result = string.Empty;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                using (GZipStream decompressedStream = new GZipStream(ms, CompressionMode.Decompress))
                {
                    using (StreamReader sr = new StreamReader(decompressedStream, Encoding.GetEncoding(encoding)))
                    {
                        result = sr.ReadToEnd();
                    }
                }
            }
            return result;
        }

        public string WriteGzipToBase64(string content, string encoding = "utf-8")
        {
            byte[] bytes = WriteGzip(content,encoding);
            return Convert.ToBase64String(bytes);
        }

        //
        private byte[] WriteGzip(string str, string encoding = "utf-8")
        {
            // utf-8
            byte[] rawData = System.Text.Encoding.GetEncoding(encoding).GetBytes(str);
            using (MemoryStream ms = new MemoryStream())
            {
                GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
                compressedzipStream.Write(rawData, 0, rawData.Length);
                compressedzipStream.Close();
                return ms.ToArray();
            }
        }
    }
}
